#! /usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

# 创建 flask 应用
app = Flask(__name__)
# 配置数据库地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
# 初始化数据库对象
db = SQLAlchemy(app)

# 创建表
class User(db.Model):
    """
    初始化该类时会创建 user 表，该表存在三列：id、username、email
    """
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username


if __name__ == "__main__":
    db.create_all()  # 创建数据库
    admin = User('admin', 'admin@example.com')  # 创建表实例
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)  # 将实例添加到会话
    db.session.add(guest)
    db.session.commit()  # 写入数据库
